package com.lovezy.platform.core.jwt;

import com.google.common.collect.ImmutableMap;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;
import java.util.Map;

/**
 * JWT 工具类
 * Created by jin on 2017/11/15.
 */
public class JwtUtil {

    private static final Log log = LogFactory.getLog(JwtUtil.class);

    private static Key getKeyInstance() {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary("jin1995jianjian666");
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
        return signingKey;
    }

    /**
     * 使用HS256签名算法和生成的signingKey最终的Token,claims中是有效载荷
     */
    public static String createJavaWebToken(Map<String, Object> claims) {
        return Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS256, getKeyInstance()).compact();
    }

    //解析Token，同时也能验证Token，当验证失败返回null
    public static Map<String, Object> parserJavaWebToken(String jwt) {
        try {
            Map<String, Object> jwtClaims =
                    Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwt).getBody();
            return jwtClaims;
        } catch (Exception e) {
            log.error("json web token verify failed");
            return null;
        }
    }

    public static String createToken(String mid,String tokenId) {
        return Jwts.builder().setClaims(ImmutableMap.of("mid",mid,"token",tokenId,"time",new Date())).signWith(SignatureAlgorithm.HS256, getKeyInstance()).compact();
    }

    public static void main(String[] args) {
//        String token = createJavaWebToken(ImmutableMap.of("mid", "123123123"));
//        System.out.println(token);
        Map<String, Object> a = parserJavaWebToken("eyJhbGciOiJIUzI1NiJ9.eyJtaWQiOiI5ZDI5YWU5Njc5NmE0ZTZkOTZkY2ZhMmZjNDg2MGQ3YyJ9.Wi00JQl2a9kGUaFZujmdv3NvT4CR2DbfKxtIQsphsgc");
        Object mid = a.get("mid");
        System.out.println(mid);
    }

}
